package com.zjdiepu.www.diepu.biz.impl;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.diepu.www.client.partner.proxy.request.OpenCardbackReasonRequest;
import com.diepu.www.client.partner.xhh.enums.PartnerErrorCode;
import com.diepu.www.client.proxy.partner.common.DiepuOtherAttachments;
import com.diepu.www.client.proxy.partner.common.DiepuOtherAttachmentsResponse;
import com.diepu.www.client.proxy.partner.common.DzApplyDiviInfo;
import com.diepu.www.client.proxy.partner.common.YwBusinessBuyerInfo;
import com.diepu.www.client.proxy.partner.common.YwBusinessCarInfo;
import com.diepu.www.client.proxy.partner.common.YwBusinessLoanInfo;
import com.diepu.www.client.proxy.partner.request.divi.ApplyDiviProxyRequest;
import com.diepu.www.client.proxy.partner.request.divi.SynDiviAttachmentsRequest;
import com.diepu.www.client.proxy.partner.request.own.DiepuOtherAttachmentsRequest;
import com.diepu.www.client.proxy.partner.request.own.DiepuYwOpenCardHzicbcRequest;
import com.zjdiepu.www.base.enums.status.ApplyDiviStatus;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.status.OpenCardStatus;
import com.zjdiepu.www.common.consts.SystemConsts;
import com.zjdiepu.www.diepu.biz.IDiepuProxyService;
import com.zjdiepu.www.enums.TransferAttachStatus;
import com.zjdiepu.www.proxy.biz.impl.BaseProxyService;
import com.zjdiepu.www.proxy.biz.transfer.INewTransaction;
import com.zjdiepu.www.proxy.biz.transfer.ITransferYwOrdernoBankService;
import com.zjdiepu.www.proxy.dao.own.HzDao;
import com.zjdiepu.www.proxy.model.dto.transfer.TransferDzApplyDivi;
import com.zjdiepu.www.proxy.model.dto.transfer.TransferOtherAttachments;
import com.zjdiepu.www.proxy.model.dto.transfer.TransferYwBusinessBuyer;
import com.zjdiepu.www.proxy.model.dto.transfer.TransferYwBusinessCar;
import com.zjdiepu.www.proxy.model.dto.transfer.TransferYwBusinessLoan;
import com.zjdiepu.www.proxy.model.dto.transfer.TransferYwOpenCardHzicbc;
import com.zjdiepu.www.proxy.model.dto.transfer.TransferYwOrdernoBank;
import com.zjdiepu.www.proxy.model.ext.transfer.TransferOtherAttachmentsExt;
import com.zjdiepu.www.proxy.model.ext.transfer.TransferYwOpenCardHzicbcExt;
import com.zjdiepu.www.security.exception.BasePartnerException;
/**
 * 与碟普交互接口实现
 * @author xiongxiaotun
 *
 */
@Service
public class DiepuProxyServiceImpl extends BaseProxyService implements IDiepuProxyService {
	private org.slf4j.Logger Logger = LoggerFactory.getLogger(getClass());
	@Resource
	private ITransferYwOrdernoBankService transferYwOrdernoBankService;
	@Resource
	private INewTransaction newTransaction;
	
	@Override
	public boolean synDiviAttachments(SynDiviAttachmentsRequest synDiviAttachmentsRequest) throws BasePartnerException {
		String busiId = synDiviAttachmentsRequest.getBusiId();
		List<TransferYwOrdernoBank> transferYwOrdernoBank = transferYwOrdernoBankService.getByBusiId(busiId);
		
		if(null == transferYwOrdernoBank || StringUtils.isBlank(transferYwOrdernoBank.get(0).getOrdeRno())) {
			throw new BasePartnerException(PartnerErrorCode.ORDER_NO_MISSING.getCode(), PartnerErrorCode.ORDER_NO_MISSING.getName());
		}
		//增加定时任务
		String orderno = transferYwOrdernoBank.get(0).getOrdeRno();
		newTransaction.saveSynAttachementsDiepu(orderno, busiId);//1、同步附件列表（2分钟后）；
		newTransaction.saveFileDownloadQiniu(orderno, busiId);//2、下载附件（5分钟后）；
		return true;
	}
	
	@Override
	public boolean saveApplyDivi(ApplyDiviProxyRequest request) throws BasePartnerException {
		String busiId = request.getBusiId();
		
		List<TransferYwOrdernoBank> transferYwOrdernoBank = transferYwOrdernoBankService.getByBusiId(busiId);
		if(null == transferYwOrdernoBank || StringUtils.isBlank(transferYwOrdernoBank.get(0).getOrdeRno())) {
			
			// 另一种处理：添加一条空白申请记录，并生成订单号
			throw new BasePartnerException(PartnerErrorCode.ORDER_NO_MISSING.getCode(), PartnerErrorCode.ORDER_NO_MISSING.getName());
		}
		
		String orderno = transferYwOrdernoBank.get(0).getOrdeRno();
		DzApplyDiviInfo divi = request.getDivi();
		TransferDzApplyDivi transferDzApplyDivi = new TransferDzApplyDivi();
		if(null != divi) {
			BeanUtils.copyProperties(divi, transferDzApplyDivi);
			transferDzApplyDivi.setAssessOrg(divi.getAssessOrg());
			transferDzApplyDivi.setBankOrderNo(orderno); //合作机构订单号
			TransferDzApplyDivi transferDzApplyDivi_ = new TransferDzApplyDivi();
			transferDzApplyDivi_.setBankOrderNo(orderno);
			transferDzApplyDivi_.setDpStatus(DpStatus.NORMAL.getCode());
			transferDzApplyDivi_.setOrderSql("`CREATED` DESC");
			transferDzApplyDivi_ = transferDzApplyDiviMapper.selectRefined(transferDzApplyDivi_);
			boolean insert = false;
			String applyDiviFlag = "0"; //新申请
			if(null == transferDzApplyDivi_) {
				insert = true;
			} else {
				applyDiviFlag = "1";//继续申请
				Integer applyDiviStatus = transferDzApplyDivi_.getApplyDiviStatus();
				if(ApplyDiviStatus.SHEN_QING_SHI_BAI.getCode().equals(applyDiviStatus)) {
					transferDzApplyDiviMapper.deleteByPrimaryKey(transferDzApplyDivi_.getId()); //删除失败分期
					insert = true;
				}
			}
			transferDzApplyDivi.setApplyDiviFlag(applyDiviFlag);
			if(insert) {
				transferDzApplyDivi.initInsertData(SystemConsts.DEFAULT_ID, "申请分期接口");
				transferDzApplyDiviMapper.insert(transferDzApplyDivi);
			} else {
				transferDzApplyDivi.initUpdateData(SystemConsts.DEFAULT_ID, "申请分期接口");
				transferDzApplyDiviMapper.updateByPrimaryKeySelective(transferDzApplyDivi);
			}
		}
		
		YwBusinessBuyerInfo buyer = request.getBuyer();
		if(null != buyer) {
			TransferYwBusinessBuyer transferYwBusinessBuyer = new TransferYwBusinessBuyer();
			BeanUtils.copyProperties(buyer, transferYwBusinessBuyer);
			String buyerId = transferYwBusinessBuyer.getId();
			TransferYwBusinessBuyer transferYwBusinessBuyer_ = transferYwBusinessBuyerMapper.selectByPrimaryKey(buyerId);
			if(null == transferYwBusinessBuyer_) {
				transferYwBusinessBuyer.initInsertData(SystemConsts.DEFAULT_ID, "申请分期接口");
				transferYwBusinessBuyer.setId(buyerId);
				transferYwBusinessBuyerMapper.insert(transferYwBusinessBuyer);
			} else {
				transferYwBusinessBuyer.initUpdateData(SystemConsts.DEFAULT_ID, "申请分期接口");
				transferYwBusinessBuyerMapper.updateByPrimaryKeySelective(transferYwBusinessBuyer);
			}
		}
		
		YwBusinessLoanInfo loan = request.getLoan();
		if(null != loan) {
			TransferYwBusinessLoan transferYwBusinessLoan = new TransferYwBusinessLoan();
			BeanUtils.copyProperties(loan, transferYwBusinessLoan);
			String loanId = transferYwBusinessLoan.getId();
			TransferYwBusinessLoan transferYwBusinessLoan_ = transferYwBusinessLoanMapper.selectByPrimaryKey(loanId);
			if(null == transferYwBusinessLoan_) {
				transferYwBusinessLoan.initInsertData(SystemConsts.DEFAULT_ID, "申请分期接口");
				transferYwBusinessLoan.setId(loanId);
				transferYwBusinessLoanMapper.insert(transferYwBusinessLoan);
			} else {
				transferYwBusinessLoan.initUpdateData(SystemConsts.DEFAULT_ID, "申请分期接口");
				transferYwBusinessLoanMapper.updateByPrimaryKeySelective(transferYwBusinessLoan);
			}
		}
		
		YwBusinessCarInfo car = request.getCar();
		if(null != car) {
			TransferYwBusinessCar transferYwBusinessCar = new TransferYwBusinessCar();
			BeanUtils.copyProperties(car, transferYwBusinessCar);
			String carId = transferYwBusinessCar.getId();
			TransferYwBusinessCar transferYwBusinessCar_ = transferYwBusinessCarMapper.selectByPrimaryKey(carId);
			if(null == transferYwBusinessCar_) {
				transferYwBusinessCar.initInsertData(SystemConsts.DEFAULT_ID, "申请分期接口");
				transferYwBusinessCar.setId(carId);
				transferYwBusinessCarMapper.insert(transferYwBusinessCar);
			} else {
				transferYwBusinessCar.initUpdateData(SystemConsts.DEFAULT_ID, "申请分期接口");
				transferYwBusinessCarMapper.updateByPrimaryKeySelective(transferYwBusinessCar);
			}
		}
		//增加定时任务
		newTransaction.saveSynAttachementsDiepu(orderno, busiId);//2分钟
		newTransaction.saveFileDownloadQiniu(orderno, busiId);//5分钟
		newTransaction.saveApplyDiviHzicbcFirst(orderno, busiId);//30分钟
		return true;
	}
	@Override
	public void saveOpenCardSuccess() {
		TransferYwOpenCardHzicbcExt transferYwOpenCardHzicbcExt=new TransferYwOpenCardHzicbcExt();
		transferYwOpenCardHzicbcExt.setOpenCardStatus(OpenCardStatus.KAI_KA_CHENG_GONG.getCode());
		transferYwOpenCardHzicbcExt.setInformStatus("0");
		transferYwOpenCardHzicbcExt.setBaseWhere();
		transferYwOpenCardHzicbcExt.withOutPage();
		List<TransferYwOpenCardHzicbc> list=transferYwOpenCardHzicbcMapper.selectByExt(transferYwOpenCardHzicbcExt);
		TransferYwOrdernoBank transferYwOrdernoBank =null;
		if(list!=null&&list.size()>0){
			for (TransferYwOpenCardHzicbc transferYwOpenCardHzicbc : list) {
				// 插入一个 10分钟之后的【向主程序通知开卡成功】的定时任务；
				transferYwOrdernoBank = new TransferYwOrdernoBank();
				transferYwOrdernoBank.setBusiId(transferYwOpenCardHzicbc.getBusiId());
				transferYwOrdernoBank.setDpStatus(DpStatus.NORMAL.getCode());
				transferYwOrdernoBank.setOrderSql("`CREATED` DESC");
				transferYwOrdernoBank = transferYwOrdernoBankMapper.selectRefined(transferYwOrdernoBank);
				if(transferYwOrdernoBank!=null){
					newTransaction.saveOpenCardSuccess(transferYwOrdernoBank.getOrdeRno(), transferYwOrdernoBank.getBusiId());
				}
			}
		}
	}
	@Override
	public void saveOpenCardFail() {
		TransferYwOpenCardHzicbcExt transferYwOpenCardHzicbcExt=new TransferYwOpenCardHzicbcExt();
		transferYwOpenCardHzicbcExt.setOpenCardStatus(OpenCardStatus.KAI_KA_SHI_BAI.getCode());
		transferYwOpenCardHzicbcExt.setInformStatus("0");
		transferYwOpenCardHzicbcExt.setBaseWhere();
		transferYwOpenCardHzicbcExt.withOutPage();
		List<TransferYwOpenCardHzicbc> list=transferYwOpenCardHzicbcMapper.selectByExt(transferYwOpenCardHzicbcExt);
		TransferYwOrdernoBank transferYwOrdernoBank =null;
		if(list!=null&&list.size()>0){
			for (TransferYwOpenCardHzicbc transferYwOpenCardHzicbc : list) {
				// 插入一个 10分钟之后的【向主程序通知开卡成功】的定时任务；
				transferYwOrdernoBank = new TransferYwOrdernoBank();
				transferYwOrdernoBank.setBusiId(transferYwOpenCardHzicbc.getBusiId());
				transferYwOrdernoBank.setDpStatus(DpStatus.NORMAL.getCode());
				transferYwOrdernoBank.setOrderSql("`CREATED` DESC");
				transferYwOrdernoBank = transferYwOrdernoBankMapper.selectRefined(transferYwOrdernoBank);
				if(transferYwOrdernoBank!=null){
					newTransaction.saveOpenCardFailTask(transferYwOrdernoBank.getOrdeRno(), transferYwOrdernoBank.getBusiId());
				}
			}
		}
	}
	@Autowired
	private HzDao hzDao;
	/**
	 * 从主程序获取附件列表 及其定时任务
	 * @param dataId
	 */
	@Transactional(isolation=Isolation.READ_COMMITTED,timeout=60,propagation=Propagation.REQUIRED,readOnly=false)
	public boolean saveTransferOtherAttachments(String dataId, String orderno){
		try {
			DiepuOtherAttachmentsRequest diepuOtherAttachmentsRequest=new DiepuOtherAttachmentsRequest();
			diepuOtherAttachmentsRequest.setDataId(dataId);
			DiepuOtherAttachmentsResponse response=diepuService.selectOtherAttachmentsByDataId(diepuOtherAttachmentsRequest);
			
			List<DiepuOtherAttachments> currentAttachments=response.getOtherAttachmentsList();
			TransferOtherAttachmentsExt transferOtherAttachmentsExt=new TransferOtherAttachmentsExt();
			transferOtherAttachmentsExt.setBaseWhere();
			transferOtherAttachmentsExt.withOutPage();
			transferOtherAttachmentsExt.setDataid(dataId);
			List<TransferOtherAttachments> transferOtherAttachments=transferOtherAttachmentsMapper.selectByExt(transferOtherAttachmentsExt);
			Set<String> exists = transferOtherAttachments.stream().map(item -> item.getId()).collect(Collectors.toSet());
			
			if(CollectionUtils.isNotEmpty(currentAttachments)){
				for (DiepuOtherAttachments currentAttachment : currentAttachments) {
					String currentId = currentAttachment.getId();
					
					
					boolean flag = false;
					for (TransferOtherAttachments transferOtherAttachment : transferOtherAttachments) {
						String fileName = currentAttachment.getFileName();
						if(currentAttachment.getId().equals(transferOtherAttachment.getId()) 
								&& (StringUtils.isBlank(fileName) 
										|| fileName.equals(transferOtherAttachment.getFileName()))){ //如果文件名为空或者文件名没有改变，不进行同步
							flag = true;
						}
					}
					TransferOtherAttachments toSaveTransferOtherAttachment=new TransferOtherAttachments();
					BeanUtils.copyProperties(currentAttachment, toSaveTransferOtherAttachment);
					toSaveTransferOtherAttachment.setTransferAttachStatus(TransferAttachStatus.WEI_XIA_ZAI.getCode());
					toSaveTransferOtherAttachment.setBankOrderNo(orderno);
					if(!exists.contains(currentId)){ //新的附件
						//TODO 添加时有重复ID问题
						transferOtherAttachmentsMapper.insert(toSaveTransferOtherAttachment);
					} else if(!flag) {//旧的附件，并且有修改
						transferOtherAttachmentsMapper.updateByPrimaryKey(toSaveTransferOtherAttachment);
					}
					exists.remove(currentId); 
				}
			}
			if(CollectionUtils.isNotEmpty(exists)) { //删除了的附件
				for(String removeId : exists) {
					//删除附件
					String sqlXml = "delete from transfer_other_attachments where id = '" + removeId + "'";
					hzDao.deleteWhereSqlXmls(sqlXml);
//					transferOtherAttachmentsMapper.deleteByPrimaryKey(removeId);
				}
			}
		} catch(BasePartnerException e) {
			Logger.error("saveTransferOtherAttachments happend customer exception.errorCode is {}, errorMsg is {}.",e.getErrorCode(), e.getErrorMsg());
			return false;
		} catch(Exception e) {
			Logger.error("saveTransferOtherAttachments happend exception.",e);
			return false;
		}
		return true;
	}
	
	@Override
	public boolean saveNoticeOpenCardSuccess(String datasId) {
		boolean flag=false;
		Integer tryCount=0;
		try{
			TransferYwOpenCardHzicbc transferYwOpenCardHzicbc=new TransferYwOpenCardHzicbc();
			transferYwOpenCardHzicbc.setBusiId(datasId);
			transferYwOpenCardHzicbc =transferYwOpenCardHzicbcMapper.selectRefined(transferYwOpenCardHzicbc);
			if(transferYwOpenCardHzicbc!=null){
				DiepuYwOpenCardHzicbcRequest diepuYwOpenCardHzicbcRequest1=new DiepuYwOpenCardHzicbcRequest();
				BeanUtils.copyProperties(transferYwOpenCardHzicbc, diepuYwOpenCardHzicbcRequest1);
				flag=diepuService.noticeOpenCardSuccess(diepuYwOpenCardHzicbcRequest1);
				if(flag==true){
					DiepuYwOpenCardHzicbcRequest diepuYwOpenCardHzicbcRequest=new DiepuYwOpenCardHzicbcRequest();
					BeanUtils.copyProperties(transferYwOpenCardHzicbc, diepuYwOpenCardHzicbcRequest);
					// 成功：更新 transfer_yw_open_card_hzicbc的inform_status 为1；
					transferYwOpenCardHzicbc.setInformStatus("1");
					tryCount=transferYwOpenCardHzicbc.getTryCount()+1;
					transferYwOpenCardHzicbc.setTryCount(tryCount);
					transferYwOpenCardHzicbc.setOpenCardStatus(OpenCardStatus.KAI_KA_CHENG_GONG.getCode());
					int count=transferYwOpenCardHzicbcMapper.updateByPrimaryKeySelective(transferYwOpenCardHzicbc);
					if(count>0){
						flag=true;
					}
					diepuYwOpenCardHzicbcRequest=null;
				}
			}
		}catch(Exception e){
			// 失败：插入一个 10分钟之后的【向主程序通知开卡成功】的定时任务；
//			TransferYwOrdernoBank transferYwOrdernoBank = new TransferYwOrdernoBank();
//			transferYwOrdernoBank.setBusiId(datasId);
//			transferYwOrdernoBank.setDpStatus(DpStatus.NORMAL.getCode());
//			transferYwOrdernoBank.setOrderSql("`CREATED` DESC");
//			transferYwOrdernoBank = transferYwOrdernoBankMapper.selectRefined(transferYwOrdernoBank);
			if(tryCount<10){
				List<TransferYwOrdernoBank> transferYwOrdernoBank = transferYwOrdernoBankService.getByBusiId(datasId);
				newTransaction.saveOpenCardSuccess(transferYwOrdernoBank.get(0).getOrdeRno(), transferYwOrdernoBank.get(0).getBusiId());
			}
		}
		if(flag==false){
			// 失败：插入一个 10分钟之后的【向主程序通知开卡成功】的定时任务；
//			TransferYwOrdernoBank transferYwOrdernoBank = new TransferYwOrdernoBank();
//			transferYwOrdernoBank.setBusiId(datasId);
//			transferYwOrdernoBank.setDpStatus(DpStatus.NORMAL.getCode());
//			transferYwOrdernoBank.setOrderSql("`CREATED` DESC");
//			transferYwOrdernoBank = transferYwOrdernoBankMapper.selectRefined(transferYwOrdernoBank);
			if(tryCount<10){
				List<TransferYwOrdernoBank> transferYwOrdernoBank = transferYwOrdernoBankService.getByBusiId(datasId);
				newTransaction.saveOpenCardSuccess(transferYwOrdernoBank.get(0).getOrdeRno(), transferYwOrdernoBank.get(0).getBusiId());
			}
		}
		return flag;
	}
	@Override
	public boolean saveNoticeOpenCardFail(String datasId,Integer openCardStatus,String backReason) {
		boolean flag=false;
		OpenCardbackReasonRequest openCardbackReasonRequest=new OpenCardbackReasonRequest();
		openCardbackReasonRequest.setBusiId(datasId);
		openCardbackReasonRequest.setOpenCardStatus(openCardStatus);
		openCardbackReasonRequest.setBacknote(backReason);
		try {
			flag=diepuService.openCardBackReason(openCardbackReasonRequest);
			if(flag==true){
				TransferYwOpenCardHzicbc transferYwOpenCardHzicbc=new TransferYwOpenCardHzicbc();
				transferYwOpenCardHzicbc.setBusiId(datasId);
				transferYwOpenCardHzicbc.setDpStatus(DpStatus.NORMAL.getCode());
				transferYwOpenCardHzicbc=transferYwOpenCardHzicbcMapper.selectRefined(transferYwOpenCardHzicbc);
				if(transferYwOpenCardHzicbc==null){
					throw new BasePartnerException(PartnerErrorCode.BUSI_MISSING.getCode(), PartnerErrorCode.BUSI_MISSING.getName());
				}
				transferYwOpenCardHzicbc.setInformStatus("1");
				transferYwOpenCardHzicbcMapper.updateByPrimaryKeySelective(transferYwOpenCardHzicbc);
			}
		} catch (BasePartnerException e) {
			List<TransferYwOrdernoBank> transferYwOrdernoBank = transferYwOrdernoBankService.getByBusiId(datasId);
			newTransaction.saveOpenCardFailTask(transferYwOrdernoBank.get(0).getOrdeRno(), transferYwOrdernoBank.get(0).getBusiId());
			flag=false;
		}
		return flag;
	}
}
